proc init { } {
    global param1
    global beep
    global param2
    global param3
    global pound

    set beep 0
    set pound 0

    set param1(interruptPrompt) true
    set param1(abortKey) *
    set param1(terminationKey) #


    set param2(interruptPrompt) true
    set param2(abortKey) *
    set param2(terminationKey) #
    set param2(dialPlanTerm) true

    set param3(interruptPrompt) true
    set param3(abortKey) *
    set param3(terminationKey) #

}

proc init_ConfigVars { } {

    global accountLen
    global pinLen
    global retryCnt
    global operatorNum
    global warnTime
    global totalLang

    set accountLen [string trim [infotag get cfg_avpair uid-len]]
    set pinLen [string trim [infotag get cfg_avpair  pin-len]]
    set retryCnt [string trim [infotag get  cfg_avpair retry-count]]
    set operatorNum [string trim [infotag get cfg_avpair  redirect-number]]
    set warnTime [string trim [infotag get cfg_avpair  warning-time]]

    #Language related variables
    set totalLang [string trim [infotag get med_total_languages]]
}

proc init_perCallVars { } {

    global selectCnt
    global count
    global fcnt
    global ani
    global callId
    global dontPlayAmount
    global destBusy
    global noTimeLimit
    global promptFlag
    global promptFlag2
    global noPlay
    global outgoingDisconnect
    global commandHandle
    global destination
    global playAccount
    global aniAuth
    global dnis
    global quality

    set selectCnt 0
    set count 0
    set fcnt 0
    set dontPlayAmount 0
    set destBusy 0
    set noTimeLimit 0
    set promptFlag 0
    set promptFlag2 0
    set noPlay 0
    set outgoingDisconnect 0
    set commandHandle ""
    set destination ""
    set playAccount 0
    set aniAuth 0
    set quality 0

    set ani [infotag get leg_ani]
    set callId  [infotag get leg_incoming]
    set dnis [infotag get leg_dnis]

}

proc act_Setup { } {
    global totalLang
    global param1
    global ani
    global callId
    global pound
    global dnis

    set pound 0
    init_perCallVars
    infotag set med_language 1

    leg setupack leg_incoming
    leg proceeding leg_incoming
    leg connect leg_incoming

        set avList(h323-ivr-out,0) "accessNumber:$dnis"
    aaa accounting update leg_incoming -a avList

    if {$ani != ""} {
        puts "\nDEBUG (callId=$callId, ani=$ani): act_setup: Start ANI authorization\n"
        set avsend(h323-ivr-out,0) "aaaType:ANI"
        set avsend(h323-ivr-out,1) "accessNumber:$dnis"
        aaa authorize $ani "" $ani "" leg_incoming avsend
    } else {
        puts "\nDEBUG (callId=$callId, ani=$ani): act_setup: ANI is not recognized\n"
        #Lang selection
        if { $totalLang < 1 } {
              act_Cleanup
              return
        }
        if { $totalLang == 1 } {
             fsm setstate CARDSELECTION
             act_GetCard
             return
        }
        set param1(maxDigits) 1
        leg collectdigits leg_incoming param1
        media play leg_incoming %c2 _welcome.au _lang_sel2.au %c1 _welcome.au _lang_sel1.au
        fsm setstate  LANGSELECTION
    }
}

proc act_Authenticated { } {
    global totalLang
    global param1
    global ani
    global callId
    global account
    global pin
    global aniAuth
    global NoPlayDuration
    global NoPlayMoney
    global NoPlayAll

    set ivrtype {}
    set username {}
    set NoPlayDuration 0
    set NoPlayMoney 0
    set NoPlayAll 0

    set status [infotag get evt_status]
    if {$status == "ao_000"} {

        if { [infotag get aaa_avpair_exists h323-return-code] } {
             set returnCode [infotag get aaa_avpair h323-return-code]
             puts "\nDEBUG (callId=$callId, ani=$ani): act_Authenticated: Return Code from Radius Server = $returnCode\n"

             if { $returnCode == 1 } {
                  puts "\nDEBUG: ANI: (callId=$callId, ani=$ani): act_ANIAuthorized: ani authorization is OK\n"
                  set aniAuth 1
                  set num [infotag get aaa_avpair_exists h323-ivr-in]
                  if { $num != 0 } {
                       set test [infotag get aaa_avpair h323-ivr-in]
                       puts "DEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: AVPAIR ->  $test"
                       foreach pairs [split $test]  {
                               set value_list [split $pairs :]
                               set key [lindex $value_list 0]
                               set value [lindex $value_list 1]
                               if { $key == "ivrtype" } {
                                    set ivrtype $value
                               } elseif { $key == "username" } {
                                    set account $value
                               }
                       }
                       if { $ivrtype == "time" } {
                            puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: Play ONLY creditTime\n"
                            set NoPlayMoney 1
                            set pin ""
                            fsm setstate GETDEST
                            act_FirstAuthorized
                            return
                       } elseif { $ivrtype == "money" } {
                            puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: Play ONLY creditAmount\n"
                            set NoPlayDuration 1
                            set pin ""
                            fsm setstate GETDEST
                            act_FirstAuthorized
                            return
                       } elseif { $ivrtype == "all" } {
                            puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: Play creditTime and creditAmount\n"
                            set pin ""
                            fsm setstate GETDEST
                            act_FirstAuthorized
                            return
                       } elseif { $ivrtype == "nothing" } {
                            puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: No play creditTime and creditAmount\n"
                            set NoPlayMoney 1
                            set NoPlayDuration 1
                            set pin ""
                            fsm setstate GETDEST
                            act_FirstAuthorized
                            return
                       } else {
                            puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: Unknown ivrType. Play creditAmount\n"
                            set NoPlayDuration 1
                            set pin ""
                            fsm setstate GETDEST
                            act_FirstAuthorized
                            return
                       }
                  } else {
                     puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: No h323-ivr-in\n"
                     set account $ani
                     set pin ""
                     fsm setstate GETDEST
                     act_FirstAuthorized
                     return
                  }
             } else {
                  puts "\nDEBUG: ANI: (callId=$callId, ani=$ani): act_ANIAuthorized: not ani authorization, play greetings\n"
                  #Lang selection
                  if { $totalLang < 1 } {
                       act_Cleanup
                       return
                  }
                  if { $totalLang == 1 } {
                       fsm setstate CARDSELECTION
                       act_GetCard
                       return
                  }
                  set param1(maxDigits) 1
                  leg collectdigits leg_incoming param1
                  media play leg_incoming %c2 _welcome.au _lang_sel2.au %c1 _welcome.au _lang_sel1.au
                  fsm setstate  LANGSELECTION
             }

         } else {
             puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: Authorisation failed, no returnCode from Radius. End connection\n"
            media play leg_incoming _no_aaa.au
            fsm setstate CALLDISCONNECT
            return
         }
    } else {
        puts "\nDEBUG (callId=$callId, ani=$ani): act_ANIAuthorized: Radius sent ACCESS REJECT! End connection\n"
        media play leg_incoming _no_aaa.au
        fsm setstate CALLDISCONNECT
        return
    }
}


proc act_LangSelect { } {
    global param1
    global selectCnt
    global retryCnt
    global ani
    global callId

    set status [infotag get evt_status]
    #Collect Success ...matched pattern
    if {$status == "cd_005"} {
        set test [infotag get evt_dcdigits]
        puts "DEBUG: (callId=$callId, ani=$ani):  act_LangSelect: User send $test"
        if { [regexp {^[0-9]$} $test] } {
            set status [infotag set med_language $test]
            if { ($status == "language not supported") ||
                 ($status == "language not specified in configuration") } {
                 incr selectCnt
                 if {$selectCnt < $retryCnt} {
                      #Get the map and use it...not this way ???
                      set param1(maxDigits) 1
                      leg collectdigits leg_incoming param1
                      puts "DEBUG (callId=$callId, ani=$ani):  act_LangSelect: Wrong language selected, attempt = $selectCnt, try again"
                      media play leg_incoming %c2 _welcome.au _lang_sel2.au %c1 _welcome.au _lang_sel1.au
                      fsm setstate same_state
                      return
                  } else {
                      puts "DEBUG (callId=$callId, ani=$ani):  act_LangSelect: Wrong language selected, attempt = $selectCnt, no attepts left, end connection"
                      media play leg_incoming %c2 _generic_final.au
                      fsm setstate CALLDISCONNECT
                        return
                  }
            }
            #Get the card No
            act_GetCard
        } else {
             puts "DEBUG:  act_LangSelect: wrong args"
             set param1(maxDigits) 1
             leg collectdigits leg_incoming param1
             media play leg_incoming %c2 _welcome.au _lang_sel2.au %c1 _welcome.au _lang_sel1.au
             fsm setstate same_state
             return
        }
    }

    if { $status == "cd_001" || \
         $status == "cd_002" } {

        incr selectCnt
        if {$selectCnt < $retryCnt} {
            leg collectdigits leg_incoming param1
            puts "DEBUG (callId=$callId, ani=$ani):  act_LangSelect: Timeout or aborted. Try again"
            media play leg_incoming  %c2 _no_lang_sel.au %s1000 %c2 _lang_sel2.au %s1000 %c1 _lang_sel1.au

            fsm setstate same_state
        } else {
            puts "DEBUG (callId=$callId, ani=$ani):  act_LangSelect: Timeout or aborted. No attempts left. End connections"
            media play leg_incoming %c2 _generic_final.au
            fsm setstate CALLDISCONNECT
        }
    }
}

proc act_GetCard { } {

    global cardLen
    global accountLen
    global pinLen
    global count
    global param1
    global promptFlag
    global ani
    global callId
    global totalLang

    set cardLen [expr $accountLen + $pinLen]
    set param1(maxDigits)  $cardLen

    leg collectdigits leg_incoming param1
    if {$count == 0} {
        if { $totalLang == 1} {
               media play leg_incoming _welcome.au _enter_card_num.au
        } else {
               media play leg_incoming _enter_card_num.au
        }
    } else {
        if {$promptFlag == 1 } {
            puts "DEBUG (callId=$callId, ani=$ani): act_GetCard: Invalid digits entered\n"
            media play leg_incoming  _invalid_digits.au
        }
        if {$promptFlag == 2 } {
            puts "DEBUG (callId=$callId, ani=$ani): act_GetCard: No such username in the database!\n"
            media play leg_incoming _auth_fail.au
        }
        if {$promptFlag == 3} {
            puts "DEBUG (callId=$callId, ani=$ani): act_GetCard: No digits entered\n"
            media play leg_incoming _no_card_entered.au
        }
    }

}

proc act_GotCardNumber { } {
    global count
    global retryCnt
    global promptFlag
    global account
    global pin
    global accountLen
    global cardLen
    global ani
    global callId
    global dnis

    set status [infotag get evt_status]

    set avsend(h323-ivr-out,0) "aaaType:FIRST"
    set avsend(h323-ivr-out,1) "accessNumber:$dnis"


    # Do we need to calculate len ???
    if {$status == "cd_005"} {
        set number [infotag get evt_dcdigits]
        set numberLen [ string length $number ]

        if { $numberLen == 10 } {
            set account [ string range $number 0 5]
            set pin [ string range $number 6 10 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } elseif { $numberLen == 11 } {
            set account [ string range $number 0 6]
            set pin [ string range $number 7 11 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } elseif { $numberLen == 12 } {
            set account [ string range $number 0 7]
            set pin [ string range $number 8 12 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } elseif { $numberLen == 13 } {
            set account [ string range $number 0 8]
            set pin [ string range $number 9 13 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } elseif { $numberLen == 14 } {
            set account [ string range $number 0 9]
            set pin [ string range $number 10 14 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } elseif { $numberLen == 15 } {
            set account [ string range $number 0 10]
            set pin [ string range $number 11 15 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } elseif { $numberLen == 16 } {
            set account [ string range $number 0 11]
            set pin [ string range $number 12 16 ]
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } else {
            puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Invalid digits entered - $number"
            incr count
            set promptFlag 1
            if {$count < $retryCnt} {
                act_GetCard
                fsm setstate same_state
            } else {
               # media play leg_incoming _final.au
                media play leg_incoming _invalid_digits.au
                fsm setstate CALLDISCONNECT
            }
        }
        return
    }

    #timeout
    if {$status == "cd_001"} {
        set number [infotag get evt_dcdigits]
        set numberLen [ string length $number ]
        if { $numberLen == 0 } {
            incr count
            set promptFlag 3
            if {$count < $retryCnt} {
                puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Timeout (no digits entered), go to act_GetCard"
                act_GetCard
                fsm setstate same_state
            } else {
                puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Timeout (no digits entered), no attempts left, end connection"
                media play leg_incoming  _final.au
                fsm setstate CALLDISCONNECT
            }
            return
        }
        if { $numberLen == $cardLen } {
            set account [ string range $number 0 [expr $accountLen -1]]
            set pin [ string range $number $accountLen [expr $cardLen -1]]
            puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Timeout (eneterd account=$account, pin=$pin). Lenght OK. Go to first authorize"
            #Do authorize
            aaa authorize $account $pin $ani "" leg_incoming avsend
        } else {
            incr count
            set promptFlag 1
            if {$count < $retryCnt} {
                puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Timeout (eneterd account=$account, pin=$pin). Lenght bad, one more attempt. Go to act_GetCard"
                act_GetCard
                fsm setstate same_state
            } else {
                puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Timeout (eneterd account=$account, pin=$pin). Lenght bad, no attempts left, end connection"
                media play leg_incoming _final.au
                fsm setstate CALLDISCONNECT
            }
        }
        return
    }

    #Aborted
    if {$status == "cd_002"} {
        set number [infotag get evt_dcdigits]
        puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Aborted (entered $number). Go to act_GetCard"
        act_GetCard
        fsm setstate same_state
        return
    }

    #timeout/fail(disconnected)/invalid_no
    #shd we play a diff prompt for disconnected...what is disconnected???
    if {($status == "cd_001") ||
        ($status == "cd_007") ||
        ($status == "cd_006")} {
        set number [infotag get evt_dcdigits]
        incr count
        set promptFlag 3
        if {$count < $retryCnt} {
            puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Unknown trouble (entered $number). One more attempt, go to act_GetCard"
            act_GetCard
            fsm setstate same_state
        } else {
            puts "DEBUG (callId=$callId, ani=$ani): act_GotCardNumber: Unknown trouble (entered $number). No attempts left, end connection"
            media play leg_incoming  _final.au
            fsm setstate CALLDISCONNECT
            return
        }
        return
    }
}


proc act_FirstAuthorized { } {

    global count
    global retryCnt
    global promptFlag
    global ani
    global callId
    global NoPlayDuration
    global NoPlayMoney
    global NoPlayAll
    global account
    global pin

    set ivrtype {}
    set NoPlayDuration 0
    set NoPlayMoney 0
    set NoPlayAll 0

    set status [infotag get evt_status]

    puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: status = $status\n"

    if { $status == "ao_000" } {

         if { [infotag get aaa_avpair_exists h323-return-code] } {
             set returnCode [infotag get aaa_avpair h323-return-code]
             puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Return Code from Radius Server = $returnCode\n"
             switch $returnCode {
                     1 {
                         puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: authorize successfuly\n"
                         set num [infotag get aaa_avpair_exists h323-ivr-in]
                         if { $num != 0 } {
                              set test [infotag get aaa_avpair h323-ivr-in]
                              puts "DEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: AVPAIR ->  $test"
                              foreach pairs [split $test]  {
                                 set value_list [split $pairs :]
                                 set key [lindex $value_list 0]
                                 set value [lindex $value_list 1]
                                 if { $key == "ivrtype" } {
                                      set ivrtype $value
                                 }
                              }
                              if { $ivrtype == "time" } {
                                   puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Play ONLY creditTime\n"
                                   set NoPlayMoney 1
                                   act_GetDest
                                   return
                              } elseif { $ivrtype == "money" } {
                                   puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Play ONLY creditAmount\n"
                                   set NoPlayDuration 1
                                   act_GetDest
                                   return
                              } elseif { $ivrtype == "all" } {
                                   puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Play creditTime and creditAmount\n"
                                   act_GetDest
                                   return
                              } elseif { $ivrtype == "nothing" } {
                                   puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: No play creditTime and creditAmount\n"
                                   set NoPlayMoney 1
                                   set NoPlayDuration 1
                                   act_GetDest
                                   return
                              } else {
                                   puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Unknown ivrType. Play creditAmount\n"
                                   set NoPlayDuration 1
                                   act_GetDest
                                   return
                              }
                         } else {
                            puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: No h323-ivr-in\n"
                            act_GetDest
                            return
                         }
                       }
                     10 {
                         incr count
                         set promptFlag 2
                         if { $count < $retryCnt } {
                              puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: No such username in the database, attempt = $count, try again\n"
                              act_GetCard
                              fsm setstate CARDSELECTION
                              return
                         } else {
                              puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: No such username in the database, attempt = $count, end connection\n"
                              media play leg_incoming _auth_fail.au
                              fsm setstate CALLDISCONNECT
                         }
                        }
                     20 {
                          incr count
                          set promptFlag 2
                          if { $count < $retryCnt } {
                               puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Incorect PIN code, attempt = $count, try again\n"
                               act_GetCard
                               fsm setstate CARDSELECTION
                               return
                          } else {
                               puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Incorect PIN code, attempt = $count, end connection\n"
                               media play leg_incoming _auth_fail.au
                              fsm setstate CALLDISCONNECT
                         }
                        }
                     30 {
                          puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: No money in account. End connection\n"
                          media play leg_incoming _zero_bal.au
                          fsm setstate CALLDISCONNECT
                         }
                     40 {
                          puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Account disabled by operator. End connection\n"
                          media play leg_incoming  _account_closed.au
                          fsm setstate CALLDISCONNECT
                        }
                     50 {
                          puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Card already online. End connection\n"
                          media play leg_incoming _card_online.au
                          fsm setstate CALLDISCONNECT
                        }
                     80 {
                          puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Denied access phone. End connection\n"
                          media play leg_incoming _block_access_phone.au _call_to_office.au
                          fsm setstate CALLDISCONNECT
                        }
                default {
                          #media play leg_incoming _no_aaa.au
                          media play leg_incoming _zero_bal.au
                          fsm setstate CALLDISCONNECT
             }          }
         } else {
             puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: No ReturnCode from Radius. End connection\n"
             media play leg_incoming _no_aaa.au
             fsm setstate CALLDISCONNECT
             return
         }
    } else {
            puts "\nDEBUG (callId=$callId, ani=$ani): act_FirstAuthorized: Radius sent Access Reject! End connection\n"
            media play leg_incoming _no_aaa.au
            fsm setstate CALLDISCONNECT
            return
    }

}

proc act_TerminateSetup { } {

    global commandHandle
    global callId
    global ani

    if {[infotag get evt_digit] == "#" } {

        # Pound is pressed during setup

        set DURATION 1000

        set duration [infotag get evt_digit_duration]


            # Longpound detected

            set returnCode [command terminate $commandHandle]

            puts "\n supress any tones that might be active \n"
            puts "DEBUG: act_TerminateSetup:(callId=$callId, ani=$ani): returnCode = $returnCode\n"
            playtone leg_incoming "tn_none"

            if {$returnCode == 0} {

                # Continue to wait for the ev_setup_done

            } elseif {$returnCode == 1} {

                # The call setup command is done, no event will be returned

                #act_JustGetDest
                act_Just_GetDest
                fsm setstate GETDEST

            } elseif {$returnCode == 2} {

                # Invalid command.  Maybe setup had not been initiated,
                # attempt to wait for it.

                #fsm setstate PLACECALL
                #act_JustGetDest
                act_Just_GetDest
                fsm setstate GETDEST
            }
    } else {

        # Ignore non-pound key entry

        fsm setstate same_state
    }
}

proc act_GetDest { } {
    global fcnt
    global promptFlag2
    global destBusy
    global pound
    global ani
    global callId
    global param4
    global amt
    global playAccount
    global quality

    if { [infotag get aaa_avpair_exists h323-credit-amount] } {
        set amt [infotag get aaa_avpair h323-credit-amount]
        puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: amt = $amt"
    } else {
        puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: No amt from radius. End connections, play no_aaa.au"
        media play leg_incoming _no_aaa.au
        fsm setstate CALLDISCONNECT
        return
    }

    set param4(maxDigits) 1
    set param4(terminationKey) #
    set param4(interruptPrompt) true

    leg collectdigits leg_incoming param4

    puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: quality = $quality\n"

    if {$fcnt == 0} {
        if {$amt == 0} {
            puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: amt = 0. End connection"
            media play leg_incoming _zero_bal.au
            fsm setstate CALLDISCONNECT
        } elseif {$amt > 999999.99} {
            puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: amt > 999999.99"
            media play leg_incoming _invalid_amt.au _dollars.au %s1000 _enter_dest.au
        } elseif {$destBusy == 1} {
            set digits [infotag get evt_dcdigits]
            puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: destBusy=$destBusy, digits=$digits"
            set destBusy 0
            media play leg_incoming _dest_busy.au
        } elseif {$pound == 1} {
            puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: pound=$pound"
            if { $playAccount == 1 } {
                 puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Play account and enter destination.\n"
                 media play leg_incoming _you_have.au %a$amt %s1000 _enter_dest.au
            } else {
                 puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Play enter destination only.\n"
                 media play leg_incoming _enter_dest.au
            }
        } else {
            if { $playAccount == 1 } {
                 puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Play account and enter destination.\n"
                 media play leg_incoming _you_have.au %a$amt %s1000 _enter_dest.au
            } else {
                 puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Play enter destination only.\n"
                 media play leg_incoming _enter_dest.au
            }
        }

    } else {
         puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: promptFlag2=$promptFlag2"
         if {$promptFlag2 == 1 || $promptFlag2 == 0} {
             puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Timeout. Play reenter destination"
             media play leg_incoming _no_dest_entered.au %s1000 _reenter_dest.au
         }
         if {$promptFlag2 == 2} {
             puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Second authorize failed"
             media play leg_incoming _author_fail.au
         }
         if {$promptFlag2 == 3} {
             media play leg_incoming _no_dest_entered.au
         }
         if {$promptFlag2 == 4} {
             puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Invalid Destination"
             media play leg_incoming _invalid_dest.au
         }
         if {$promptFlag2 == 6} {
             puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Destination busy. Try again"
             media play leg_incoming _dest_busy.au
         }
         if {$promptFlag2 == 8} {
             puts "DEBUG (callId=$callId, ani=$ani): act_GetDest: Abort."
             media play leg_incoming  _enter_dest.au
         }
          if {$promptFlag2 == 9} {
             media play leg_incoming _not_enuf.au _enter_dest.au
        }
    }
}

proc act_DigitAnalyse { } {
   global ani
   global callId
   global digit_dest
   global param2
   global account
   global pin
   global dnis
   global aniAuth
   global promptFlag2
   global fcnt

   set status [infotag get evt_status]

   if {$status == "cd_005"} {
       set digit_dest [infotag get evt_dcdigits]
       puts "\nDEBUG (callId=$callId, ani=$ani): act_DigitAnalyse: digit_dest = $digit_dest\n"
       if { $digit_dest == "*" } {
            #set param5(maxDigits) 1
            #set param5(interruptPrompt) true
            #set param5(ignoreInitialTermKey) true

            set param2(maxDigits) 1
            set param2(enableReporting) true
            set param2(interruptPrompt) true
            set param2(ignoreInitialTermKey) true
            set param2(terminationKey) #

            leg collectdigits leg_incoming param2
            #media play leg_incoming  _menu.au
            media play leg_incoming _menu_quality.au
            fsm setstate MENU
            #act_MainMenu


       } elseif { $digit_dest == "" } {
             puts "\nDEBUG (callId=$callId, ani=$ani): act_DigitAnalyse: go to act_GetDest\n"

             if { $aniAuth == 1 } {
                  set avsend(h323-ivr-out,0) "aaaType:ANI"
                  set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                  aaa authorize $ani "" $ani "" leg_incoming -a avsend
                  fsm setstate AN_AUTHORIZE
                  set playAccount 0
                  return
             } else {
                  set avsend(h323-ivr-out,0) "aaaType:FIRST"
                  set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                  aaa authorize $account $pin $ani "" leg_incoming avsend
                  fsm setstate AN_AUTHORIZE
                  set playAccount 0
                  return
             }
       } else {
            puts "\nDEBUG (callId=$callId, ani=$ani): act_DigitAnalyse: entering destination\n"
            set param2(maxDigits) 14
            set param2(enableReporting) true
            set param2(interruptPrompt) true
            set param2(ignoreInitialTermKey) true
            set param2(terminationKey) #
            leg collectdigits leg_incoming param2

            fsm setstate DIGIT_COLLECT
       }
   } else {
      puts "\nDEBUG (callId=$callId, ani=$ani): act_DigitAnalyse: any fucking state\n"
      if { $aniAuth == 1 } {
                  set avsend(h323-ivr-out,0) "aaaType:ANI"
                  set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                  aaa authorize $ani "" $ani "" leg_incoming -a avsend
                  set playAccount 0
                  fsm setstate AN_AUTHORIZE
                  return
      } else {
                  set avsend(h323-ivr-out,0) "aaaType:FIRST"
                  set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                  aaa authorize $account $pin $ani "" leg_incoming avsend
                  set playAccount 0
                  fsm setstate AN_AUTHORIZE
                  return
      }
   }
}

proc act_GotDest { } {
    global fcnt
    global retryCnt
    global promptFlag2
    global destination
    global ani
    global callId
    global account
    global pin
    global dontPlayAmount
    global digit_dest
    global aniAuth
    global dnis
    global quality
    global origDest

    set status [infotag get evt_status]
    puts "\nDEBUG (callId=$callId, ani=$ani): act_GotDest: aniAuth = $aniAuth, status = $status, fcnt=$fcnt, dontPlayAmount = $dontPlayAmount"
    #matched dialplan
    if {$status == "cd_004" || $status == "cd_005" || $status == "cd_009"} {
          set destination "$digit_dest[infotag get evt_dcdigits]"
          set origDest $destination
          set destLen [ string length $destination ]
          if { $destLen >= 8 } {
               puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: destination=$destination  go to second authorize"
               if { $quality == 1 } {
                    set avsend(h323-ivr-out,2) "quality:special"
               }
               set avsend(h323-ivr-out,0) "aaaType:SECOND"
               set avsend(h323-ivr-out,1) "accessNumber:$dnis"
               aaa authorize $account $pin  $ani $destination leg_incoming avsend
               return
          } else {
               incr fcnt
               if {$fcnt < $retryCnt} {
                   puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: Invalid digits entered: $destLen\n"
                   set promptFlag2 4
                   if { $aniAuth == 1 } {
                        set avsend(h323-ivr-out,0) "aaaType:ANI"
                        set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                        aaa authorize $ani "" $ani "" leg_incoming -a avsend
                   } else {
                        set avsend(h323-ivr-out,0) "aaaType:FIRST"
                        set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                        aaa authorize $account $pin "" "" leg_incoming avsend
                   }
                   fsm setstate AN_AUTHORIZE

                   return
               } else {
                   media play leg_incoming _generic_final.au
                   fsm setstate CALLDISCONNECT
               }
          }
    }

    #aborted
    if {$status == "cd_002"} {
        #if {$dontPlayAmount == 1} {
        puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: User pressed abort key. Do not play amount, go to act_Just_GetDest"
        set promptFlag2 8
        act_Just_GetDest
        #} else {
        #    puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: User pressed abort key. Play amount, go to act_GetDest"
        #    set promptFlag2 8
        #    act_GetDest
        #}
        #fsm setstate same_state
        fsm setstate GETDEST
        return
    }

    incr fcnt
    if {$fcnt < $retryCnt} {
        if {$status == "cd_001" } {
            puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: The digit collection timed out. Try again."
            set promptFlag2 1
        }
        if {$status == "cd_006" } {
            puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: The digit collection failed, because the number collected was invalid (not dial-peer)."
            set promptFlag2 4
        }
        if {$status == "cd_007" } {
            puts "DEBUG (callId=$callId, ani=$ani): act_GotDest: The digit collection was terminated, because an ev_disconnected event was received on the call leg"
            set promptFlag2 3
        }
        #if {$dontPlayAmount == 1} {
        act_Just_GetDest
        #} else {
        #    act_GetDest
        #}
        fsm setstate same_state
    } else {
        media play leg_incoming _generic_final.au
        fsm setstate CALLDISCONNECT
    }


}

proc act_MainMenu {} {
   global amt
   global param4
   global callId
   global ani
   global destination
   global digit_dest
   global account
   global pin
   global playAccount
   global NoPlayMoney
   global dnis
   global aniAuth
   global quality

   puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu, destination = $destination, account = $account, pin = $pin, NoPlayMoney = $NoPlayMoney\n"
   set status [infotag get evt_status]
   puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: status = $status\n"

   if {$status == "cd_005" || $status == "cd_004" || $status == "cd_009"} {
       set menuSelect [infotag get evt_dcdigits]
       puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: menuSelect = $menuSelect\n"
       if { $menuSelect == 1 } {
            if { $NoPlayMoney == 1 } {
                 set playAccount 0
                 media play leg_incoming _no_option_entered.au
                 fsm setstate GETDEST
                 act_GetDest
                 return
            } else {
                 puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: Play Account\n"
                 if { [infotag get aaa_avpair_exists h323-credit-amount] } {
                       puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: aaa_avpair_exists h323-credit-amount\n"
                       set playAccount 1
                       fsm setstate GETDEST
                       act_GetDest
                       return
                 } else {
                       puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: Another AAA\n"
                       if { $aniAuth == 1 } {
                            set avsend(h323-ivr-out,0) "aaaType:ANI"
                            set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                            aaa authorize $ani "" $ani "" leg_incoming -a avsend
                            set playAccount 1
                            fsm setstate AN_AUTHORIZE
                            return
                       } else {
                            set avsend(h323-ivr-out,0) "aaaType:FIRST"
                            set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                            aaa authorize $account $pin $ani "" leg_incoming avsend
                            set playAccount 1
                            fsm setstate AN_AUTHORIZE
                            return
                       }
                 }
            }
       } elseif { $menuSelect == 2 && $destination != "" } {
            puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: Try Redial\n"
            set avsend(h323-ivr-out,0) "aaaType:SECOND"
            set avsend(h323-ivr-out,1) "accessNumber:$dnis"
            if { $quality == 1 } {
                    set avsend(h323-ivr-out,2) "quality:special"
               }
            aaa authorize $account $pin  $ani $destination leg_incoming avsend
            fsm setstate SECONDAUTHORIZE
       } elseif { $menuSelect == 3 } {
            puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: VoiceQuality\n"
                 set quality 1
                 media play leg_incoming _quality.au
                 fsm setstate QUALITY
                 return
       } else {
            puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: Unknown option\n"
            if { [infotag get aaa_avpair_exists h323-credit-amount] } {
                 set playAccount 0
                 media play leg_incoming _entered_invalid_option.au
                 fsm setstate GETDEST
                 act_GetDest
                 return
            } else {

                 if { $aniAuth == 1 } {
                      set avsend(h323-ivr-out,0) "aaaType:ANI"
                      set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                      aaa authorize $ani "" $ani "" leg_incoming -a avsend
                      set playAccount 0
                      fsm setstate AN_AUTHORIZE
                      return
                 } else {
                      set avsend(h323-ivr-out,0) "aaaType:FIRST"
                      set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                      aaa authorize $account $pin $ani "" leg_incoming avsend
                      set playAccount 0
                      fsm setstate AN_AUTHORIZE
                      return
                 }
            }
       }
   } else {
       puts "\nDEBUG (callId=$callId, ani=$ani): MainMenu: No option Entered\n"
       if { [infotag get aaa_avpair_exists h323-credit-amount] } {
            set playAccount 0
            media play leg_incoming _no_option_entered.au
            fsm setstate GETDEST
            act_GetDest
            return
       } else {
           if { $aniAuth == 1 } {
                set avsend(h323-ivr-out,0) "aaaType:ANI"
                set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                aaa authorize $ani "" $ani "" leg_incoming -a avsend
                set playAccount 0
                media play leg_incoming _no_option_entered.au
                fsm setstate AN_AUTHORIZE
                return
           } else {
                set avsend(h323-ivr-out,0) "aaaType:FIRST"
                set avsend(h323-ivr-out,1) "accessNumber:$dnis"
                aaa authorize $account $pin $ani "" leg_incoming avsend
                set playAccount 0
                media play leg_incoming _no_option_entered.au
                fsm setstate AN_AUTHORIZE
                return
           }
       }
   }
}

proc act_SecondAuthorized { } {
    global account
    global destination
    global noTimeLimit
    global creditTime
    global warnTime
    global promptFlag2
    global fcnt
    global retryCnt
    global noPlay
    global commandHandle
    global ani
    global callId
    global NoPlayDuration
    global phonePrefix

    set callInfo(accountNum) $account
    set callInfo(alertTimer) 25
    set phonePrefix {}

    set status [infotag get evt_status]

    if { $status == "ao_000" } {
        if { [infotag get aaa_avpair_exists h323-credit-time] } {
            set creditTime [infotag get aaa_avpair h323-credit-time]
            puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: Second authorize succssesfuly, creditTime = $creditTime"
        } else {
            puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: Second authorize fails. Disconnect"
            media play leg_incoming _no_aaa.au
            fsm setstate CALLDISCONNECT
            return
        }

        if { [infotag get aaa_avpair_exists h323-ivr-in] } {
            set test [infotag get aaa_avpair h323-ivr-in]
            puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: AVPAIR ->  $test\n"
            foreach pairs [split $test]  {
                    set value_list [split $pairs :]
                    set key [lindex $value_list 0]
                    set value [lindex $value_list 1]
                    if { $key == "timeout" } {
                         set timeout $value
                    } elseif { $key == "phone_prefix" } {
                         set phonePrefix $value
                    }
            }
        }

        if { [infotag get aaa_avpair_exists h323-return-code] } {
            set returnCode [infotag get aaa_avpair h323-return-code]
            puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: returnCode=$returnCode\n"

            switch -regexp $returnCode {
                           {1}  {
                                 if {$creditTime == "uninitialized"} {
                                     puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: creditTime is uninitialized. End connection"
                                     media play leg_incoming _no_aaa.au
                                     fsm setstate CALLDISCONNECT
                                     return
                                 } elseif {$creditTime == "unlimited"} {
                                     puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: creditTime is unlimited"
                                     set noTimeLimit 1
                                     # play mesg only if time left is  20 secs > warntime
                                 } elseif {$creditTime == "-1"} {
                                     set noTimeLimit 1
                                     puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: creditTime is unlimited, noTimeLimit = $noTimeLimit, go to act_CallSetup"
                                     act_CallSetup
                                     return
                                     # play mesg only if time left is  20 secs > warntime
                                 } elseif {[expr $creditTime - $warnTime] < 20} {
                                     set noPlay 1
                                     puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: creditTime($creditTime) < warnTime($warnTime)"
                                     media play leg_incoming _you_have.au %t$creditTime
                                 } else {
                                    puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: creditTime = $creditTime\n"
                                    if { $NoPlayDuration == 1 } {
                                         act_CallSetup
                                         return
                                     } else {
                                         if { $timeout != 0 } {
                                              media play leg_incoming _you_have.au %t$timeout
                                         } else {
                                              media play leg_incoming _you_have.au %t$creditTime
                                         }
                                     }
                                 }
                                }
                           {50} {
                                 puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: Card already online. End connections\n"
                                 media play leg_incoming _card_online.au
                                 fsm setstate CALLDISCONNECTa
                                }
                           {60 || 62} {
                                 puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: not enough money for this call\n"
                                 act_Just_GetDest
                                 fsm setstate GETDEST
                                }
                           {75} {
                                 puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: access not configured for the given destination or zone blocked\n"
                                 act_Just_GetDest
                                 fsm setstate GETDEST
                                }
            }
        } else {
            #No return code from radius
            puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: No returnCode from Radius. end connection\n"
            media play leg_incoming _no_aaa.au
            fsm setstate CALLDISCONNECT
            return
        }
    } else {
        puts "\nDEBUG (callId=$callId, ani=$ani): act_SecondAuthorized: authorization failed."
        media play leg_incoming _no_aaa.au
        fsm setstate CALLDISCONNECT
        return
    }
}

proc act_CallSetup { } {
    global destination
    global account
    global pound
    global commandHandle
    global outgoingDisconnect
    global param3
    global ani
    global callId
    global dnis
    global phonePrefix

    set param3(interruptPrompt) true
    set param3(enableReporting) true

    if { ($pound == 1) || ($outgoingDisconnect == 1) } {
         set callInfo(newguid) true
    }

    set callInfo(accountNum) $account
    ## HACK (try to substitute ANI for outgoing leg)
    set callInfo(originationNum) "8123357385"
    ## End Hack
    set destination "$phonePrefix$destination"
    puts "DEBUG (callId=$callId, ani=$ani): act_CallSetup: Try make call. Destination: $destination"

     #for longpound
    leg setup $destination callInfo leg_incoming
    set commandHandle [infotag get last_command_handle]
    puts "DEBUG (callId=$callId, ani=$ani): act_CallSetup: commandHandle = $commandHandle\n"
}

proc act_CallSetupDone { } {
    global warnTime
    global creditTime
    global noPlay
    global noTimeLimit
    global param3
    global pound
    global outgoingDisconnect
    global ani
    global callId
    global quality
    global origDest
        global dnis

    set status [infotag get evt_status]
    puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: status = $status"
    set param3(interruptPrompt) true
    set param3(enableReporting) true


    if { $quality == 1 } {
         set avList(h323-ivr-out,0) "quality:special"
    }

    set avList(h323-ivr-out,1) "origDest:$origDest"
    set avList(h323-ivr-out,2) "accessNumber:$dnis"
    aaa accounting update leg_outgoing -a avList

    if {$status == "ls_000"} {
        puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call is active or was successful"
        set pound 0
        set outgoingDisconnect 0

        if { ($noTimeLimit == 1) ||
             ($creditTime == "unlimited") ||
             ($creditTime == "uninitialized") ||
             ($creditTime == "-1") } {
            #no timer
            puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: Time duration set to unlimited"
        } else {
            if {$creditTime < $warnTime} {
                if {$noPlay == 1} {
                    set timerDuration [expr $creditTime - 1]
                    puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: creditTime < warnTime, noPlay=$noPlay. Start timer $timerDuration"
                    timer start leg_timer  [expr $creditTime - 1] leg_incoming
                } else {
                    set timerDuration [expr $warnTime - 4]
                    puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: creditTime < warnTime, noPlay=$noPlay. Start timer $timerDuration"
                    timer start leg_timer [expr $warnTime - 4] leg_incoming
                }
                fsm setstate CALLLASTACTIVE

            } else {
                set timerDuration [expr $creditTime - $warnTime]
                puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: Start timer $timerDuration"
                set delay [expr $creditTime - $warnTime]
                timer start leg_timer $delay leg_incoming
                fsm setstate CALLACTIVE
            }
        }
        #for longpound
        leg collectdigits leg_incoming param3
        return
    } else {
       switch -regexp $status {
            {ls_001} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The outgoing call leg was looped"
                      act_DestBusy
                      return
                     }
            {ls_002} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call setup timed out (meaning that the destination phone was alerting, but no one answered)"
                      act_DestBusy
                      return
                     }
            {ls_003} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call setup failed due to a lack of resources in the network"
                      act_DestBusy
                      return
                     }
            {ls_004} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call setup failed because of an invalid number"
                      act_DestBusy
                      return
                     }
            {ls_005} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call setup failed for reasons other than a lack of resources or an invalid number"
                      act_DestBusy
                      return
                     }
            {ls_006} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: Unused; setup failure"
                      act_DestBusy
                      return
                     }
            {ls_007} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The destination was busy"
                      act_DestBusy
                      return
                     }
            {ls_008} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The incoming side of the call disconnected"
                      act_DestBusy
                      return
                     }
            {ls_009} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The outgoing side of the call disconnected."
                      act_DestBusy
                      return
                     }
            {ls_010} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The conferencing or connecting of the two call legs failed."
                      act_DestBusy
                      return
                     }
            {ls_011} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: Supplementary services internal failure"
                      act_DestBusy
                      return
                     }
            {ls_012} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: Supplementary services failure"
                      act_DestBusy
                      return
                     }
            {ls_013} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: Supplementary services failure. Inbound call leg was disconnected"
                      act_DestBusy
                      return
                     }
            {ls_014} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call was handed off to another application."
                      act_DestBusy
                      return
                     }
            {ls_015} {
                      puts "DEBUG (callId=$callId, ani=$ani): act_CallSetupDone: The call setup was terminated by an application request"
                      act_DestBusy
                      return
                     }
       }
    }
}


proc act_HandleOutgoing { } {
    global outgoingDisconnect
    global ani
    global callId

    if { [infotag get evt_legs] == [infotag get leg_outgoing] } {
        puts "\nDEBUG (callId=$callId, ani=$ani): act_HandleOutgoing: Outgoing Disconnected"
        connection destroy con_all
        set outgoingDisconnect 1
        return
    }
    call close
    fsm setstate CALLDISCONNECT

}


proc act_LongPound { } {
    global duration
    global pound
    global ani
    global callId

    puts "DEBUG (callId=$callId, ani=$ani): act_LongPound"

    if { [infotag get evt_digit] == "#" } {
         set pound 1
         connection destroy con_all
    } else {
         fsm setstate same_state
         return
    }
}

proc act_Just_GetDest { } {
    global fcnt
    global promptFlag2
    global pound
    global destBusy
    global param2
    global outgoingDisconnect
    global ani
    global callId

    #set param2(enableReporting) true
    #set param2(ignoreInitialTermKey) true

    set param4(maxDigits) 1
    set param4(interruptPrompt) true
    set param4(terminationKey) #

    leg collectdigits leg_incoming param4

    puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest: fcnt = $fcnt, pound = $pound"

    if {$fcnt == 0} {
        if {$outgoingDisconnect == 1} {
            media play leg_incoming _enter_dest.au
        } elseif {$destBusy == 1} {
            set destBusy 0
            media play leg_incoming _dest_busy.au
        } elseif {$pound == 1} {
              media play leg_incoming _enter_dest.au
        } else {
              media play leg_incoming _enter_dest.au
        }
    } else {
        puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest: promptFlag2=$promptFlag2"
        if {$promptFlag2 == 1} {
            puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest: Timeout. Play reenter destination"
            media play leg_incoming _no_input.au %s1000 _reenter_dest.au
        }
        if {$promptFlag2 == 2} {
            puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest: Second authorize failed"
            media play leg_incoming _author_fail.au
        }
        if {$promptFlag2 == 3} {
            puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest:
            media play leg_incoming _no_dest_entered.au
        }
        if {$promptFlag2 == 4} {
             media play leg_incoming _invalid_dest.au
        }
        if {$promptFlag2 == 5} {
             media play leg_incoming _invalid_dest.au
        }
        if {$promptFlag2 == 6} {
             puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest: Destination busy. Try again"
             media play leg_incoming _dest_busy.au
        }
        if {$promptFlag2 == 8} {
             puts "DEBUG (callId=$callId, ani=$ani): act_Just_GetDest: Abort."
             media play leg_incoming  _reenter_dest.au
        }
        if {$promptFlag2 == 9} {
             media play leg_incoming _not_enuf.au _enter_dest.au
        }

    }
}

proc act_ConnDestroyed { } {
    global dontPlayAmount
    global ani
    global callId
    global fcnt

    leg disconnect leg_outgoing
    set dontPlayAmount 1
    set fcnt 0
    puts "DEBUG (callId=$callId, ani=$ani): act_ConnDestroyed: Go to act_Just_GetDest, dontPlayAmount=$dontPlayAmount"
    act_Just_GetDest
}

proc act_DestBusy { } {
    global destBusy
    global ani
    global callId
    global promptFlag2

    #current debitcard implementation
    set destBusy 1
    set promptFlag2 6
    puts "DEBUG (callId=$callId, ani=$ani): act_DestBusy: Go to act_Just_GetDest, destBusy=$destBusy"
    fsm setstate GETDEST
    act_Just_GetDest
}

proc act_ActiveTimer { } {
    global noPlay
    global warnTime
    global creditTime
    global incoming
    global outgoing
    global ani
    global callId

    set incoming [infotag get leg_incoming]
    set outgoing [infotag get leg_outgoing]

    if {$noPlay == 1} {
        set duration [expr $creditTime -1]
        puts "\nDEBUG (callId=$callId, ani=$ani): act_ActiveTimer: noPlay=$noPlay, start timer $duration"
        timer start leg_timer  [expr $creditTime -1] leg_incoming
    } else {
        set duration [expr $warnTime - 4]
        connection destroy con_all
        puts "\nDEBUG (callId=$callId, ani=$ani): act_ActiveTimer: noPlay=$noPlay, start timer $duration"
        timer start leg_timer [expr $warnTime - 4] leg_incoming
        fsm setstate CALLWARN
    }
}

proc act_CallWarnDestroy { } {
    global warnTime
    global ani
    global callId

    puts "\nDEBUG (callId=$callId, ani=$ani): act_CallWarnDestroy: Play warn message (You have $warnTime)"
    media play leg_incoming _you_have.au %t$warnTime
}

proc act_CallWarnMedia { } {
    global incoming
    global outgoing

    connection create $incoming $outgoing
}

proc act_ConnectionDestroy { } {
    global ani
    global callId

    puts "DEBUG (callId=$callId, ani=$ani): act_ConnectionDestroy: Connection destroyed."
    connection destroy con_all
}

proc act_LastActiveTimer { } {
    global ani
    global callId

    puts "DEBUG (callId=$callId, ani=$ani): act_LastActiveTimer: Play disconnect message"
    media play leg_incoming _disconnect.au
}

proc act_Ignore { } {
# Dummy
    puts "Event Capture"
}

        proc act_Cleanup { } {
            puts "\n\nDEBUG:act_Cleanup\n\n"
            call close
        }

        requiredversion 2.0
        init

        #Get Variables
        init_ConfigVars

        #----------------------------------
        #   State Machine
        #----------------------------------
          set fsm(any_state,ev_disconnected)           "act_Cleanup           same_state"

          set fsm(CALL_INIT,ev_setup_indication)       "act_Setup            AUTHENTICATE"

          set fsm(AUTHENTICATE,ev_authorize_done)      "act_Authenticated     AUTHORIZE"

          set fsm(ONELANG,ev_media_done)               "act_GetCard           CARDSELECTION"

          set fsm(LANGSELECTION,ev_collectdigits_done) "act_LangSelect        CARDSELECTION"

          set fsm(CARDSELECTION,ev_collectdigits_done) "act_GotCardNumber     AUTHORIZE"

          set fsm(AUTHORIZE,ev_authorize_done)         "act_FirstAuthorized   GETDEST"

          set fsm(GETDEST,ev_collectdigits_done)       "act_DigitAnalyse      DIGIT_COLLECT"

          set fsm(DIGIT_COLLECT,ev_collectdigits_done) "act_GotDest           SECONDAUTHORIZE"

          set fsm(SECONDAUTHORIZE,ev_authorize_done)   "act_SecondAuthorized  PLACECALL"

          set fsm(PLACECALL,ev_media_done)             "act_CallSetup         PLACECALL"
          set fsm(PLACECALL,ev_setup_done)             "act_CallSetupDone     CALLACTIVE"
          set fsm(PLACECALL,ev_digit_end)              "act_TerminateSetup    WAITFORSETUPDONE"

          set fsm(WAITFORSETUPDONE,ev_setup_done)      "act_Just_GetDest     GETDEST"

          set fsm(CALLACTIVE,ev_leg_timer)             "act_ActiveTimer       CALLLASTACTIVE"
          set fsm(CALLACTIVE,ev_digit_end)             "act_LongPound         CONNDESTROY"
          set fsm(CALLACTIVE,ev_disconnected)          "act_HandleOutgoing    CONNDESTROY"

          set fsm(CALLLASTACTIVE,ev_leg_timer)         "act_ConnectionDestroy PLAYDISCONNECT"
          set fsm(CALLLASTACTIVE,ev_digit_end)         "act_LongPound         CONNDESTROY"

          set fsm(PLAYDISCONNECT,ev_destroy_done)      "act_LastActiveTimer   CALLDISCONNECT"

          set fsm(CALLWARN,ev_destroy_done)            "act_CallWarnDestroy   same_state"
          set fsm(CALLWARN,ev_media_done)              "act_CallWarnMedia     CALLLASTACTIVE"

          set fsm(CONNDESTROY,ev_destroy_done)         "act_ConnDestroyed     GETDEST"

          set fsm(CALLDISCONNECT,ev_media_done)        "act_Cleanup           same_state"
          set fsm(CALLDISCONNECT,ev_disconnect_done)   "act_Cleanup           same_state"
          set fsm(CALLDISCONNECT,ev_leg_timer)         "act_Cleanup           same_state"

          set fsm(MENU,ev_collectdigits_done)          "act_MainMenu          DIGIT_COLLECT"

          set fsm(AN_AUTHORIZE,ev_authorize_done)      "act_FirstAuthorized   GETDEST"
          set fsm(QUALITY,ev_media_done)               "act_Just_GetDest   GETDEST"

          fsm define fsm CALL_INIT




# Script Approval Sign
